package com.hzpd.hainan.module;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.ViewPropertyAnimation;
import com.hzpd.hainan.R;
import com.hzpd.hainan.api.InterfaceJsonfile;
import com.hzpd.hainan.model.news.NewsChannelBean;
import com.hzpd.hainan.model.news.NewsChannelEntity;
import com.hzpd.hainan.model.version.VersionBean;
import com.hzpd.hainan.model.version.VersionEntity;
import com.hzpd.hainan.model.welcome.ImageEntity;
import com.hzpd.hainan.module.version.UpdateVersionListener;
import com.hzpd.hainan.module.version.VersionCheck;
import com.hzpd.hainan.net.Factory;
import com.hzpd.hainan.services.InitService;
import com.hzpd.hainan.utils.HandlerTip;
import com.hzpd.hainan.utils.LogUtils;
import com.hzpd.hainan.utils.PageCtrl;
import com.hzpd.hainan.utils.ParamUtils;
import com.hzpd.hainan.utils.SPUtil;
import com.hzpd.hainan.utils.TUtils;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class WelcomeActivity extends Activity {
    @BindView(R.id.adflash_img_ad)
    ImageView adflashImgAd;
    @BindView(R.id.tv_welcome_skip)
    TextView tv_welcome_skip;
    protected SPUtil spu;//
    private String obj;
    private AnimatorSet animSetFadeout;
    private AnimatorSet animSetFadein;
    private String imgStr;
    int t = 3;
    Timer timer;
    // 所需的全部权限
    private static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,//照相机权限
//            Manifest.permission.READ_EXTERNAL_STORAGE,//sd卡访问权限
            Manifest.permission.VIBRATE,//震动权限 不需要申请
//            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,//定位权限
//            Manifest.permission.ACCESS_COARSE_LOCATION,//错略的位置信息
//            Manifest.permission.ACCESS_FINE_LOCATION,//定位的位置信息
            Manifest.permission.WRITE_EXTERNAL_STORAGE,//写入存储的权限;
            Manifest.permission.READ_PHONE_STATE,//写入存储的权限;
//            Manifest.permission.ACCESS_COARSE_LOCATION,//地址
    };

    private VersionCheck mVersionCheck;
    Handler hanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 100:
                    tv_welcome_skip.setText(t + "秒跳过");
//                    tv_welcome_skip.setText(t+"");
                    t--;
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        ButterKnife.bind(this);
        // 检测权限
        spu = SPUtil.getInstance();
        if(spu.getLanguage().equals("47")){
            adflashImgAd.setImageDrawable(getResources().getDrawable(R.drawable.a02));
        }else{
            adflashImgAd.setImageDrawable(getResources().getDrawable(R.drawable.a02_zhong));
        }
        InterfaceJsonfile.SITEID =spu.getLanguage();
        checkPermissions();
        Intent service = new Intent(this, InitService.class);
        service.setAction(InitService.InitAction);
        this.startService(service);
        Connector.getDatabase();
        getChannelJson();

        //检查更新
    }


    /**
     * 开屏图获取
     */
    private void getWelcomePic() {
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .welcomeAd(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ImageEntity>() {
                    @Override
                    public void onCompleted() {
                        LogUtils.i("onCompleted-->");
                    }
                    @Override
                    public void onError(Throwable e) {
                        LogUtils.i("error-->");
                        SPUtil.getInstance().setWelcome("");
                        e.printStackTrace();
                    }
                    @Override
                    public void onNext(ImageEntity entity) {
                        LogUtils.i("onnext-->"+entity.data.getImgurl());
                        StringBuilder sb = new StringBuilder();
                        for (String imgurl:entity.data.getImgurl()) {
                            sb.append(imgurl);
                            sb.append(",");
                        }
                        String imgStr2 = sb.toString();
                        SPUtil.getInstance().setWelcome(imgStr2);
                        imgStr = imgStr2;
                        setImageViewAnimation();
                    }
                });
    }

    //检测更新
    private void checkUpdata() {
        Map<String, String> map = new HashMap<>();
        Factory.provideHttpService().checkUpdata()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<VersionEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (t <= 0) {
                            goMain();
                        }
                    }
                    @Override
                    public void onNext(VersionEntity entity) {
                        updata(entity.data);
                    }
                });
    }
    //更新
    private void updata(VersionBean bean) {
        mVersionCheck = new VersionCheck(this, bean, new UpdateVersionListener() {
            @Override
            public void onVersionChecked(boolean isNeedUpdate) {
                if (!isNeedUpdate) {
                    if (t <= 0) {
                        goMain();
                    }
                }
            }
            @Override
            public void onUpdateInfoDialogDismiss(boolean isClickDownLoadButton) {
                if (!isClickDownLoadButton) {
                    if (t <= 0) {
                        goMain();
                    }
                }
            }
            @Override
            public void onDownLoadDialogDismiss(boolean isDownLoadSuccess) {
                //没有下载完成
                if (!isDownLoadSuccess) {
                    mVersionCheck.beginCheckVersion();
                }
            }
            @Override
            public void onInstallAPK() {
                finish();
            }
        });
        mVersionCheck.beginCheckVersion();
    }
    //挑转到主页面;
    public void goMain() {
        PageCtrl.start2MainActivity(this);
        finish();
        onDestroy();
    }
    private void setImageViewAnimation() {
        sendTimer();
        LogUtils.i("setImageViewAnimation");
        int dur = 1500;
        animSetFadeout = new AnimatorSet();
        ObjectAnimator oanimFadeout = ObjectAnimator
                .ofFloat(adflashImgAd, "alpha", 1.0f, 0.0f)
                .setDuration(dur);
        oanimFadeout.setInterpolator(new AccelerateInterpolator());
        animSetFadeout.play(oanimFadeout);
        animSetFadeout.setDuration(1500);
        animSetFadeout.addListener(new Animator.AnimatorListener() {
            ViewPropertyAnimation.Animator animationObject = new ViewPropertyAnimation.Animator() {
                @Override
                public void animate(View view) {
                    view.setAlpha( 0f );

                    ObjectAnimator fadeAnim = ObjectAnimator.ofFloat( view, "alpha", 0f, 1f );
                    fadeAnim.setDuration( 1500 );
                    fadeAnim.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            checkUpdata();
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    fadeAnim.start();
                }
            };
            @Override
            public void onAnimationCancel(Animator arg0) {
            }

            @Override
            public void onAnimationEnd(Animator arg0) {
                LogUtils.i("imgstr-->"+imgStr);
                if (!TextUtils.isEmpty(imgStr)) {
                    String[] imglist = imgStr.split(",");
//                    为了美观暂时不用
                    String imgurl = imglist [(int) (Math.random()*imglist.length)];
                    LogUtils.i("!=imgurl-->" + imgurl);
                    if (!TextUtils.isEmpty(imgurl)) {
//                        LogUtils.i("url-->" + imgStr);
//                        Glide.with(WelcomeActivity.this).load(imgStr).skipMemoryCache(true).animate(animationObject)
//                                .into(adflashImgAd);
                        try{
                            Glide.with(WelcomeActivity.this).load(imgurl).skipMemoryCache(true).animate(animationObject)
                                    .into(adflashImgAd);
                        }catch (Exception e){
                            LogUtils.e("Glide加载错误");
                            e.printStackTrace();
                        }
                    }

                } else {
                    try{
                        if("47".equals(spu.getLanguage())) {
                            Glide.with(WelcomeActivity.this).load(R.drawable.welcome_bg).skipMemoryCache(true).animate(animationObject)
                                    .into(adflashImgAd);
                        }else{
                            Glide.with(WelcomeActivity.this).load(R.drawable.welcome_bg_zhong).skipMemoryCache(true).animate(animationObject)
                                    .into(adflashImgAd);
                        }
                    }catch (Exception e){
                        LogUtils.e("Glide加载错误");
                        e.printStackTrace();
                    }
                }
//                animSetFadein.start();
            }

            @Override
            public void onAnimationRepeat(Animator arg0) {
            }

            @Override
            public void onAnimationStart(Animator arg0) {

            }
        });
        animSetFadeout.start();
    }

    @OnClick(R.id.tv_welcome_skip)
    public void onViewClicked(View view) {
        checkUpdata();
        goMain();
    }

    private void sendTimer() {
        timer = new Timer();
        TimerTask tt = new TimerTask() {
            @Override
            public void run() {
                if (t > -1) {
                    hanlder.sendEmptyMessage(100);
                }
            }
        };

        timer.schedule(tt, 0, 1000);

    }

    /**
     * 检测权限
     */
    private void checkPermissions() {
        RxPermissions.getInstance(getApplicationContext())
                .request(PERMISSIONS)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        if (!granted) {
                            TUtils.toast("缺少必要权限，应用无法启动");
                            // 延时跳转
                            HandlerTip.getInstance().postDelayed(1800, new HandlerTip.HandlerCallback() {
                                @Override
                                public void postDelayed() {
                                    finish();
                                }
                            });
                        }else{
                            getWelcomePic();
                        }
                    }
                });
    }
    //获取,栏目title;
    private void getChannelJson() {
        LogUtils.i("init","getChannelJson");
        Map<String, String> map = new HashMap<>();
        map.put("siteid",InterfaceJsonfile.SITEID);
        map.put("flag","1");
        Factory.provideHttpService()
                .newsChannellist(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsChannelEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsChannelEntity entity) {
                        if ("200".equals(entity.code)) {
                            return true;
                        }
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsChannelEntity>() {
                    @Override
                    public void call(NewsChannelEntity entity) {
                        List<NewsChannelBean> list = DataSupport.findAll(NewsChannelBean.class);
                        List<NewsChannelBean> listNew =entity.data;
                        int count =0;
                        if (list!=null&&entity.data!=null&&list.size()==entity.data.size()){
                            for (int i= 0; i<list.size();i++){
                                String title = list.get(i).getCnname();
                                LogUtils.e("code---"+entity.data.get(0));
                                for (int j=0;j<listNew.size();j++){
                                    String titleNew = listNew.get(j).getCnname();
                                    if (titleNew.equals(title)){
                                        count++;
                                        break;
                                    }
                                }
                            }
                            if (count!=list.size()){
                                DataSupport.deleteAll(NewsChannelBean.class);
                                DataSupport.saveAll(entity.data);
                            }
                        }else if (entity.data!=null){
                            DataSupport.deleteAll(NewsChannelBean.class);
                            List<NewsChannelBean> list1=new ArrayList<NewsChannelBean>();
                            for (int i = 0; i < listNew.size(); i++) {
                                NewsChannelBean obj=listNew.get(i);
                                LogUtils.e("list---"+listNew.get(i).getCnname());
                                LogUtils.e("list---"+listNew.get(i).getSortOrder());
                                String title = listNew.get(i).getCnname();
                                if ("共和".equals(title)||"贵德".equals(title)||"贵南".equals(title)||"同德".equals(title)||"兴海".equals(title)
                                ||"གུང་ཧོ།".equals(title)||"ཁྲི་ཀ།".equals(title)||"ཀོས་ནན།".equals(title)||"ཐུན་ཏེ།".equals(title)||"ཞིན་ཧེ།".equals(title)){
                                    obj.setIschoice("0");
                                }
                                obj.setSortOrder((i));
                                list1.add(i,obj);
                            }
                            DataSupport.saveAll(list1);
                            for (NewsChannelBean newsChannelBean : list1) {
                                LogUtils.e("list---"+newsChannelBean.getSortOrder());
                            }

                        }

                        List<NewsChannelBean> list2 = DataSupport.findAll(NewsChannelBean.class);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable-->"+throwable.toString());
                    }
                });

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        hanlder.removeCallbacks(null);
    }
}
